﻿using System;
using System.Linq;
using RBOSS.Data;

namespace RBOSS.CreditCard
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "CreditCardService" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select CreditCardService.svc or CreditCardService.svc.cs at the Solution Explorer and start debugging.
    public class CreditCardService : ICreditCardService
    {
        private readonly CreditCardDBEntities1 _dataContext = new CreditCardDBEntities1();
        public bool VerifyCreditCard(CreditCardInfo creditCardInfo)
        {
            var creditCard = (from c in _dataContext.CreditCards
                              where
                                  c.CreditCardNo == creditCardInfo.CreditCardNumber && c.ExpiryDate == creditCardInfo.ExpiredDate &&
                                  c.SecurityPin == creditCardInfo.SecurityNumber
                              select c).FirstOrDefault();

            return (creditCard != null) && (creditCard.Balance >= creditCardInfo.Amount);
            
        }

        public bool SaveCreditCard(CreditCardInfo creditCardInfo)
        {
            try
            {
                var creditCard = (from c in _dataContext.CreditCards
                                  where
                                      c.CreditCardNo == creditCardInfo.CreditCardNumber && c.ExpiryDate == creditCardInfo.ExpiredDate &&
                                      c.SecurityPin == creditCardInfo.SecurityNumber
                                  select c).FirstOrDefault();
                if (creditCard != null)
                {
                    creditCard.Balance = creditCard.Balance - creditCardInfo.Amount;
                    _dataContext.SaveChanges();
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
    }
}
